import os
from models import *
from google.appengine.api import users
class LoginControl():

  def CheckLogin(self,role,externalself):
    notlogged = True
    permisiondeny = True
    user = users.get_current_user()
    if str(user)=='None':
      notlogged = True
    else:
      queryuser = CustomUser.all()
      queryuser.filter('user = ',user)
      if queryuser.count()>0:
        notlogged = False
        dbusers = queryuser.fetch(1)
        dbuser = dbusers[0]
        if dbuser.role==role or dbuser.role=='admin':
          permisiondeny = False
          return dbuser
        else:
          permisiondeny = True
      else:
        notlogged = True

    if os.environ.has_key('REQUEST_URI'):
      url=str(os.environ['REQUEST_URI'])+"\n\n"
    else:
      url = "http://www.clanty.com/"

    if notlogged:
      externalself.redirect(users.create_login_url(url))
      return 0

    if permisiondeny:
      #externalself.redirect("http://www.clanty.com/admin/editor/")
      return 0

  def CheckAccess(self,role):
    notlogged = False
    permisiondeny = False
    user = users.get_current_user()
    if str(user)=='None':
      notlogged = True
    else:
      queryuser = CustomUser.all()
      queryuser.filter('user = ',user)
      if queryuser.count()>0:
        dbusers = queryuser.fetch(1)
        dbuser = dbusers[0]
        if dbuser.role==role or dbuser.role=='admin':
          return dbuser
        else:
          permisiondeny = True

      else:
        notlogged = True
    if notlogged:
      dbuser = CustomUser.get('agpoZWFkZXJsaW5lchILEgpDdXN0b21Vc2VyGLmnNQw')
      return dbuser

    if permisiondeny:
      dbuser = CustomUser.get('agpoZWFkZXJsaW5lchILEgpDdXN0b21Vc2VyGLmnNQw')
      return dbuser
